package com.javafactroy.kunlong.bip.icp.ftpclient.base;

import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpConfig;
import cn.hutool.extra.ftp.FtpMode;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.javafactroy.kunlong.bip.icp.common.config.BipConfig;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

/**
 * ftp 连接对象
 *
 * @author niulibing
 */
@Data
@Component
@Slf4j
public class FtpTemplate implements Serializable {
    @Autowired
    BipConfig bipConfig;

    Ftp ftp;

    public FtpTemplate() {

    }

    /**
     * ftp客户端
     */

    public Ftp init() {
        if (ftp == null) {
            FtpConfig ftpConfig = new FtpConfig();
            log.info("{}", bipConfig);
            ftpConfig.setUser(bipConfig.getFtpUser());
            ftpConfig.setPassword(bipConfig.getFtpPassword());
            ftpConfig.setHost(bipConfig.getFtpIp());
            ftpConfig.setPort(Integer.valueOf(bipConfig.getFtpPort()));
            //ftpConfig.[[setCharset("UTF-8");
            ftp = new Ftp(ftpConfig, FtpMode.Passive);

            try {
                ftp.getClient().setFileType(FTP.BINARY_FILE_TYPE);
                ftp.getClient().setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return ftp;
    }

    public boolean rename(String from, String to) throws IOException {
        return ftp.getClient().rename(from, to);

    }

    public void close() throws IOException {
        getFtp().close();
    }

    public List<String> ls(String path) {
        return getFtp().ls(path);
    }
    public boolean mkdir(String path) {
        return getFtp().mkdir(path);
    }
}
